package com.senyint.imsdk;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

public abstract class AsyncPakcetQueueHandler<T extends Packet> {
	private Vector<T> receivedPacketQueue = new Vector<T>();
	private boolean isProcessRcvQueue = false ;
	private ExecutorService receiveExecutorService = null ;
	
	private Timer timer=new Timer();//实例化Timer类   
	
//	private Handler handler = new Handler(){
//		@Override
//		public void handleMessage(Message msg) {
//			switch(msg.what){
//			case 0:
//				this.removeMessages(msg.what);
//				startPacketQueueProcess();
//				break;
//			case 1:
//				startPacketQueueProcess();
//				break;
//			}
//			
//		}
//	};
	
	public AsyncPakcetQueueHandler(){
		final String threadId = "message-"+StringUtils.randomString(6);
		receiveExecutorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
					@Override
					public Thread newThread(Runnable runnable) {
						Thread thread = new Thread(
								runnable,
								"Connection Thread for Reveiving  " + threadId );
						thread.setPriority(Thread.MIN_PRIORITY);
						thread.setDaemon(true);
						return thread;
					}
				});
	}
	
	public void onProcessPacket(T packet) {
		receivedPacketQueue.add(packet);
		timer.schedule(new TimerTask(){
			@Override
			public void run() {
				startPacketQueueProcess();
			}
		}, 1000); 
	}
	

	private void startPacketQueueProcess() {
		if(!isProcessRcvQueue){
			isProcessRcvQueue = true ;
			receiveExecutorService.execute(new Runnable(){
				@Override
				public void run() {
					int size = 0 ;
					while ((size = receivedPacketQueue.size()) > 0 ) {
						T packet = receivedPacketQueue.firstElement();
						onProcessInBackgroud(packet);
						receivedPacketQueue.remove(packet);

						if(size == 1 ){
							isProcessRcvQueue = false ;
							break;
						}

						try {
							Thread.sleep(20L);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
		
	}

	/**
	 * 在安全线程中处理消息<br>
	 * @param message
     */
	public abstract void onProcessInBackgroud(T message) ;

	public void onHandle(Runnable r){
		receiveExecutorService.execute(r);
	}
	
}
